import { scroll } from '../tools';

class PanelBoxControler {
    
    constructor(id, cb) {
        this.$trg = null;
        this.content = null;
        this.id = id + '';
        this.page = 1;
        this.cb = cb;
        this.isLoading = false;//是否在加载中
        this.isInit = false;//初始化一次
        this.isEnd = false;//是否到底
    }

    init() {
        if(this.id.includes('.')) {
            this.$trg = $(this.id);
        }else {
            this.$trg = $('#' + this.id);
        }
        this.$content =  this.$trg.find('div').eq(0);
        !this.isInit && this._initScroll()
    }

    _checkHeight() {
        var sHeight = this.$trg.height();
        var cHeight = this.$content.height();
        if( (sHeight - cHeight) >= 0) {
            console.log('内容高度不足')
            return false;
        } else {
            this.$content.after(this._addLoading());
            return true
        }
    }
    _addLoading() {
        console.log(this);
        return `
            <div class="infinite-scroll-preloader">
                <div class="preloader"></div>
            </div>`
    }

    _removeLoading() {
        $('.infinite-scroll-preloader').remove();
    }

    _initScroll() {
        var that = this;
        if(!this._checkHeight()) return false;

        var $trg = this.$trg;
        var beforeScrollTop = $trg.scrollTop(),
        
            fn = fn || function () {};

        $trg.scroll(function () {
            //终止，不许要滚动加载
            if(that._isEnd) return
            var afterScrollTop = $(this).scrollTop(),
                delta = afterScrollTop - beforeScrollTop;
            if (delta === 0) {
                return false;
            } 

            var t = $(this).scrollTop();
            var height = $(this).find('div').eq(0).height();
            var screenHeight = $(this).height();
            var spaceToBottom = (height - (screenHeight + t));//距离底部的距离
            that._dealScroll((delta > 0 ? "down" : "up"), spaceToBottom)
            beforeScrollTop = afterScrollTop;
        }, false);
        this.isInit = true;
    }

    _dealScroll(direction, height) {
    var a = '';
        a =  direction;
            if(a == 'down' && height < 150) {
                if(!this.isLoading) {
                    this.isLoading = true;
                    
                    this.cb(this.id, this.isLoading);
                }
            }
    }
}


export default PanelBoxControler;